<?php


namespace app\common\model;


class UserChat extends BaseModel{

    protected $updateTime = false;

    public function user(){
        return $this->belongsTo('User','user_id','id')->field('id,nickname,avatar,level,education');
    }

    public function toUser(){
        return $this->belongsTo('User','to_user_id','id')->field('id,nickname,avatar,level,education');
    }

    public static function getList($userId,$toUserId,$lastChatId,$page=1,$limit=''){
        if(empty($limit)){
            $limit = config('paginate.list_rows');
        }

        $groupId = UserChatGroup::where(function($query) use($userId,$toUserId){
            return $query->where('user_id',$userId)->where('to_user_id',$toUserId);
        })->whereOr(function($query) use($userId,$toUserId){
            return $query->where('user_id',$toUserId)->where('to_user_id',$userId);
        })->value('id');

        if(empty($groupId)){
            return [];
        }
        if($lastChatId){
            return self::with(['user','toUser'])->where('group_id',$groupId)->where('id','<=',$lastChatId)->page($page,$limit)->order('created_at','desc')->select();
        }else{
            return self::with(['user','toUser'])->where('group_id',$groupId)->page($page,$limit)->order('created_at','desc')->select();
        }
    }
}